/**
 * Created by John on 2015-04-12.
 */
var mysql = require('mysql');
var DB_NAME = 'speed';

var pool  = mysql.createPool({
    host     : '127.0.0.1',
    database:'speed',
    user     : 'root',
    password : ''
});
function User(user){
    this.name = user.name;
    this.password = user.password;
};
module.exports = User;

pool.getConnection(function(err, connection) {
    var useDbSql = "USE " + DB_NAME;
    connection.query(useDbSql, function (err) {
        if (err) {
            console.log("USE Error: " + err.message);
            return;
        }
        console.log('USE succeed');
    });});


        //保存数据
User.prototype.save = function save(callback) {
    var user = {
        name: this.name,
        password: this.password,
    };
    pool.getConnection(function(err, connection) {

        var insertUser_Sql = "INSERT INTO SpeedRead(BookId,BookText) VALUES(?,?)";

        connection.query(insertUser_Sql, [user.name, user.password], function (err,result) {
            if (err) {
                console.log("insertUser_Sql Error: " + err.message);
                return;
            }
            connection.release();
            console.log("invoked[save]");
            callback(err,result);
        });
    });
};

    //根据用户名得到用户信息
User.prototype.getUserByUserName = function getUserNumByName(username, callback) {
        pool.getConnection(function(err, connection) {
    var getUserByUserName_Sql = "SELECT BookText FROM SpeedRead WHERE BookId = ?";

    connection.query(getUserByUserName_Sql, [username], function (err, result) {
        if (err) {
            console.log("getUserByUserName Error: " + err.message);
            return;
        }

        connection.release();

        console.log("invoked[getUserByUserName]");
        callback(err,result);
        });
        });
};



